<template>
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    >
    </van-nav-bar>

    <div class="name-filed-wrap">
      <van-field
        v-model="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user";
export default {
  // 组件名称
  name: "UpdateName",
  // 组件参数 接收来自父组件的数据
  props: {
    //声明接受父组件v-model传递的value数据
    value: {
      type: String,
      required: true,
    },
  },
  // 局部注册的组件
  components: {},
  // 组件状态值
  data() {
    return {
      localName: this.value,
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {},
  mounted() {},
  // 组件方法
  methods: {
    async onConfirm() {
      this.$toast.loading({
        message: "保存中",
        forbidClick: true, //禁止背景点击
      });
      try {
        //请求提交更新用户昵称
        await updateUserProfile({
          name: this.localName,
        });
        //更新成功->修改父组件的 name ->关闭弹出层
        //发布input事件，更新父组件v-model绑定的数据
        this.$emit("input", this.localName);
        /* this.$emit("update-name", this.localName); */
        this.$emit("close");
        this.$toast.success("保存成功");
      } catch (err) {
        if (err && err.response && err.response.status === 409) {
          this.$toast.fail("昵称已存在");
        }
      }
    },
  },
};
</script> 

<style scoped lang='less'>
.name-filed-wrap {
  padding: 10px;
}
</style>
